package com.tledu.production.core.interceptor;

import cn.hutool.setting.Setting;
import com.tledu.production.constant.SessionConstant;
import com.tledu.production.model.system.SysUser;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 权限拦截器
 *
 * @author Antg
 * @date 2021/8/20  12:34
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        HttpSession session = req.getSession();
        Setting setting = new Setting("myConfig.setting");
        String flag = setting.get("auth");
        //权限校验未开启直接跳过拦截
        if (flag.equals("0")) {
            return true;
        }
        //超级管理员不拦截
        SysUser user = (SysUser) session.getAttribute(SessionConstant.LOGINUSER);
        if (user.getSysRole().getRoleName().equals("超级管理员")) {
            return true;
        }
        //权限拦截
        List<String> auth = (List<String>) session.getAttribute(SessionConstant.AUTH);
        if (!auth.contains(req.getServletPath())) {
            resp.sendRedirect(req.getContextPath() + "/authError");
            return false;
        }
        return true;
    }
}
